package com.lzs.adx.web.modules.adx.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.lzs.adx.commmon.service.impl.CrudServiceImpl;
import com.lzs.adx.web.commmon.enums.ReportEnums;
import com.lzs.adx.web.commmon.utils.DateUtil;
import com.lzs.adx.web.modules.adx.dao.BackDataDao;
import com.lzs.adx.web.modules.adx.dao.ReportDao;
import com.lzs.adx.web.modules.adx.dao.ReportTotalDao;
import com.lzs.adx.web.modules.adx.dto.*;
import com.lzs.adx.web.modules.adx.entity.ReportEntity;
import com.lzs.adx.web.modules.adx.entity.ReportResultEntity;
import com.lzs.adx.web.modules.adx.entity.ReportTotalEntity;
import com.lzs.adx.web.modules.adx.service.ReportResultService;
import com.lzs.adx.web.modules.adx.service.ReportService;
import com.lzs.adx.web.modules.adx.service.ReportTotalService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 广告上报表
 *
 * @author wangzhijun 825400558@qq.com
 * @since 1.0.0 2023-06-06
 */
@Service
@Slf4j
public class ReportServiceImpl extends CrudServiceImpl<ReportDao, ReportEntity, ReportDTO> implements ReportService {

    @Autowired
    private  ReportDao reportDao;

    @Autowired
    private ReportResultService reportResultService;

    @Autowired
    private ReportTotalService reportTotalService;

    @Autowired
    private ReportTotalDao reportTotalDao;

    @Autowired
    private BackDataDao backDataDao;


    @Override
    public QueryWrapper<ReportEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String stime = (String)params.get("stime");
        String etime = (String)params.get("etime");
        String date = (String)params.get("date");
        String dspId = (String)params.get("dspId");
        Boolean resultNotNull = (Boolean)params.get("resultNotNull");


        QueryWrapper<ReportEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.ge(StringUtils.isNotBlank(stime),"create_time",stime);
        wrapper.le(StringUtils.isNotBlank(etime),"create_time",etime);
        wrapper.eq(StringUtils.isNotBlank(date),"date",date);
        wrapper.eq(StringUtils.isNotBlank(dspId),"dsp_id",dspId);
        //转化结果不为空的
        wrapper.isNull(Objects.nonNull(resultNotNull),"result_type");


        return wrapper;
    }



    @Override
    public void deleteInfo(String yesterdayStime) {
        reportDao.deleteInfo(yesterdayStime);
    }

    @Override
    public Total totalALlInfo() {
        return reportTotalDao.totalALlInfo();
    }

    @Override
    public List<PlaterChart> countProductTotal() {
        return reportTotalDao.countProductTotal();
    }

    public VistisTotalDTO countChartList(){
        VistisTotalDTO vistisTotalDTO=new VistisTotalDTO();
        List<Chart> charts = reportTotalDao.countTypeChart();
        vistisTotalDTO.setChart(charts);
        List<Chart> chartT = reportTotalDao.countTotalChart();
        vistisTotalDTO.setChartT(chartT);

        return vistisTotalDTO;
    }

    @Override
    public void weekDataCount() {
        List<ProductBackDTO> productBackDTO = backDataDao.weekDataCount();
        for (ProductBackDTO backDTO : productBackDTO) {
            synchronized (backDTO.getDspId() + backDTO.getDay()) {
                if (StringUtils.isBlank(backDTO.getType())) {
                    log.error("账户号  {} 未配置回传映射关系", backDTO.getDspId());
                    continue;
                }
                Map<String, Object> params = new HashMap<>();
                params.put("dspId", backDTO.getDspId());
                params.put("date", backDTO.getDay());
//            params.put("type", backDTO.getType());
                List<ReportTotalDTO> list = reportTotalService.list(params);
                if (CollectionUtil.isNotEmpty(list)) {
                    ReportTotalDTO reportTotalDTO = list.get(0);
                    ReportEnums reportEnums = ReportEnums.getReportEnums(backDTO.getType());
                    ReflectUtil.setFieldValue(reportTotalDTO, reportEnums.getColums(), backDTO.getTotal());
                    log.info("封装后的值为{}", JSON.toJSONString(reportTotalDTO));
                    reportTotalService.update(reportTotalDTO);
                }
            }
        }
    }

    @Override
    public List<ReportEntity> selectListByMap(String dspId,String day,Integer limit) {




        return this.baseDao.selectListByMap( dspId, day, limit);
    }


    @Transactional
    public void realDataMind(String day) {

        Map<String, Object> rrMap = new HashMap<>();
        rrMap.put("date", day);
        //总数汇总
        reportTotalHander(rrMap);


    }

    private void reportTotalHander(Map<String, Object> rrMap) {
        //总数汇总
        List<ReportTotalEntity> reportTotalEntityList = reportDao.selectReportTotalByDay(rrMap.get("date").toString());
        List<ProductBackDTO> productBackDTO = backDataDao.countDataByDay();
        Map<String, List<ProductBackDTO>> collect=null;
        if(CollectionUtil.isNotEmpty(productBackDTO)){
            collect = productBackDTO.stream().collect(Collectors.groupingBy(c -> getKey(c.getDspId(),c.getDay(),c.getType())));
        }

        for(ReportTotalEntity reportTotalEntity:reportTotalEntityList) {
            if(CollectionUtil.isNotEmpty(collect)){
                setTotalValue(reportTotalEntity, collect);
            }
            //更新
            reportTotalService.batch(reportTotalEntity);
        }
    }





    private static void setTotalValue(ReportTotalEntity reportTotalEntity, Map<String, List<ProductBackDTO>> collect) {
        //激活数
        List<ProductBackDTO> actList = collect.get(getKey(reportTotalEntity.getDspId(), reportTotalEntity.getDate(), ReportEnums.act.getType()));
        if(CollectionUtil.isNotEmpty(actList)){
            ProductBackDTO productBackDTO1 = actList.get(0);
            reportTotalEntity.setAct(productBackDTO1.getTotal());
        }else{
            reportTotalEntity.setAct(0L);
        }

        //注册数
        List<ProductBackDTO> registerList = collect.get(getKey(reportTotalEntity.getDspId(), reportTotalEntity.getDate(), ReportEnums.register.getType()));
        if(CollectionUtil.isNotEmpty(registerList)){
            ProductBackDTO productBackDTO1 = registerList.get(0);
            reportTotalEntity.setRegister(productBackDTO1.getTotal());
        }else{
            reportTotalEntity.setRegister(0L);
        }

        //次留数
        List<ProductBackDTO> retainList = collect.get(getKey(reportTotalEntity.getDspId(), reportTotalEntity.getDate(), ReportEnums.retain.getType()));
        if(CollectionUtil.isNotEmpty(retainList)){
            ProductBackDTO productBackDTO1 = retainList.get(0);
            reportTotalEntity.setRetain(productBackDTO1.getTotal());
        }else{
            reportTotalEntity.setRetain(0L);
        }

        //付费数
        List<ProductBackDTO> payList = collect.get(getKey(reportTotalEntity.getDspId(), reportTotalEntity.getDate(), ReportEnums.pay.getType()));
        if(CollectionUtil.isNotEmpty(payList)){
            ProductBackDTO productBackDTO1 = payList.get(0);
            reportTotalEntity.setPay(productBackDTO1.getTotal());
        }else{
            reportTotalEntity.setPay(0L);
        }

        //唤醒数
        List<ProductBackDTO> wakeupList = collect.get(getKey(reportTotalEntity.getDspId(), reportTotalEntity.getDate(), ReportEnums.wakeup.getType()));
        if(CollectionUtil.isNotEmpty(wakeupList)){
            ProductBackDTO productBackDTO1 = wakeupList.get(0);
            reportTotalEntity.setWakeup(productBackDTO1.getTotal());
        }else{
            reportTotalEntity.setWakeup(0L);
        }


        //关键行为
        List<ProductBackDTO> keybehaviorsList = collect.get(getKey(reportTotalEntity.getDspId(), reportTotalEntity.getDate(), ReportEnums.keybehaviors.getType()));
        if(CollectionUtil.isNotEmpty(keybehaviorsList)){
            ProductBackDTO productBackDTO1 = keybehaviorsList.get(0);
            reportTotalEntity.setKeybehaviors(productBackDTO1.getTotal());
        }else{
            reportTotalEntity.setKeybehaviors(0L);
        }
    }



    public static String getKey(String dspId,String day,String type){
        return dspId + "_" + day + "_" + type;
    }


}